package org.huanletao.ssm.service.base;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.huanletao.ssm.model.User;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * <p>
 * </p>
 * package: org.huanletao.ssm.service
 * description:
 * className: BaseService
 * author:  踏雪无痕
 * copyright: Copyright (c) 2022/9/5 9:46
 * since: 1.0.0
 */
public abstract class BaseService<T> {

    abstract protected Mapper<T> getMapper();

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    public int save(T entity) {
        return getMapper().insertSelective(entity);
    }

    /**
     * 更新
     *
     * @param entity
     * @return
     */
    public int update(T entity) {
        return getMapper().updateByPrimaryKey(entity);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Long id) {
        return getMapper().deleteByPrimaryKey(id);
    }

    /**
     * 删除
     *
     * @return
     */
    public List<T> findAll() {

        return getMapper().selectAll();
    }

    /**
     * 查询分页
     *
     * @param offset
     * @param limit
     * @return
     */
    public Page<T> selectPage(int offset, int limit,String orderBy) {
        PageHelper.offsetPage(offset, limit == 0 ? 10 : limit);
        return (Page<T>) getMapper().selectAll();
    }

    /**
     * 通过主键查询
     *
     * @param id0
     * @return
     */
    public T selectByPrimaryKey(Long id0) {
        return getMapper().selectByPrimaryKey(id0);
    }

    /**
     * 保存获取更新
     *
     * @param param
     * @return
     */
    public int saveOrUpdate(T param) {
        T entity = getMapper().selectByPrimaryKey(param);
        if (entity == null) {
            return getMapper().insertSelective(entity);
        }
        return getMapper().updateByPrimaryKeySelective(entity);
    }
}
